﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.CompositeUI;
using Microsoft.Practices.ObjectBuilder;
using PictureManager.Constant;
using System.Windows.Forms;
using Microsoft.Practices.CompositeUI.WinForms;
using WeifenLuo.WinFormsUI.Docking;
using Infrastructure.MenuService;
using PictureManager.Core;
using System.Configuration;
using System.Reflection;
using System.Net.Mail;
using System.Resources;

namespace PictureManager
{
    public class Module : ModuleInit
    {
        private WorkItem WorkItem;

        [InjectionConstructor]
        public Module([ServiceDependency] WorkItem rootWorkItem)
        {
            WorkItem = rootWorkItem;
        }
        public override void Load()
        {
            base.Load();
            AddMenuService();
            AddLogService();
        }

        private void AddLogService()
        {
            UtilLib.Util.OnLog += new EventHandler<UtilLib.LogEventArgs>(Util_OnLog);
        }

        void Util_OnLog(object sender, UtilLib.LogEventArgs e)
        {
            MailMessage msg = new System.Net.Mail.MailMessage();
            msg.To.Add("ping.chen@citi.com");

            msg.From = new MailAddress("ping.chen@citi.com", "Chet", System.Text.Encoding.UTF8);

            msg.Subject = "Error Message";
            msg.SubjectEncoding = System.Text.Encoding.UTF8;
            msg.Body = e.Exception.Message + Environment.NewLine + e.Exception.StackTrace;
            msg.BodyEncoding = System.Text.Encoding.UTF8;
            msg.IsBodyHtml = false;
            msg.Priority = MailPriority.High;
            var stream = new System.IO.MemoryStream(Infrastructure.UI.Util.PrtSc2Byte());
            msg.Attachments.Add(new Attachment(stream, e.Level.ToString()));
            SmtpClient client = new SmtpClient();
            client.Host = "smtp.citi.com";
            object userState = msg;
            try
            {
                client.SendAsync(msg, userState);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.StackTrace);
            }
            MessageBox.Show(e.Exception.Message + Environment.NewLine + e.Exception.StackTrace, e.Level.ToString(), MessageBoxButtons.OK, (MessageBoxIcon)e.Level);
        }

        private void AddMenuService()
        {
            ToolStripPanel mainMenuStripPanel = (ToolStripPanel)this.WorkItem.RootWorkItem.Items[Constants.MainToolStripPanel];
            MenuStrip menu = new MenuStrip();
            MenuConfiguration menuConfig = (MenuConfiguration)PictureManager.Core.ConfigurationManager.Instance.GetSection("MenuConfiguration");
            foreach (var menuItem in menuConfig.MenuItems)
            {
                Infrastructure.MenuService.MenuItem element = menuItem as Infrastructure.MenuService.MenuItem;
                ToolStripMenuItem item = new ToolStripMenuItem();
                item.Text = element.Text;
                item.Tag = element.Form;
                if (!UtilLib.StringUtil.IsNullOrWhitespace(element.Form))
                    item.Click += new EventHandler(childItem_Click);
                AddChildMenuItem(element, item);
                menu.Items.Add(item);
            }
            mainMenuStripPanel.Join(menu);
        }

        private void AddChildMenuItem(Infrastructure.MenuService.MenuItem element, ToolStripMenuItem item)
        {
            foreach (var childMenuItem in element.MenuItems)
            {
                Infrastructure.MenuService.MenuItem childElement = childMenuItem as Infrastructure.MenuService.MenuItem;
                ToolStripMenuItem childItem = new ToolStripMenuItem();
                childItem.Name = "meu" + childElement.ID;
                childItem.Text = childElement.Text;
                childItem.Tag = childElement.Form;
                //childItem.Image=childElement.Icon;
                if (!UtilLib.StringUtil.IsNullOrWhitespace(childElement.Form))
                    childItem.Click += new EventHandler(childItem_Click);
                AddChildMenuItem(childElement, childItem);
                item.DropDownItems.Add(childItem);
            }
        }

        void childItem_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem item = sender as ToolStripMenuItem;
            if (item == null || item.Tag == null || UtilLib.StringUtil.IsNullOrWhitespace(item.Tag.ToString())) return;
            switch (item.Tag.ToString())
            {
                case "MaintenanceView":
                    ShowDocument<frmMaintenance>();
                    break;
                case "SettingView":
                    ShowDocument<frmSetting>();
                    break;
                default:
                    break;
            }

        }

        private void ShowDocument<TypeName>() where TypeName : DockContent
        {
            try
            {
                TypeName smartPart;
                if (WorkItem.Items.Get<TypeName>(typeof(TypeName).ToString()) == null)
                    smartPart = WorkItem.Items.AddNew<TypeName>(typeof(TypeName).ToString());
                else
                    smartPart = WorkItem.Items.Get<TypeName>(typeof(TypeName).ToString()) as TypeName;

                #region DockPanel
                DockPanel dockPanel = this.WorkItem.RootWorkItem.Items.Get<DockPanel>(Constants.DockPanel);
                if (dockPanel.Contents.Any(k => k.GetType() == smartPart.GetType()))
                {
                    IDockContent content = dockPanel.Contents.FirstOrDefault(k => k.GetType() == smartPart.GetType());
                    if (content != null)
                    {
                        content.DockHandler.Activate();
                        return;
                    }
                }
                if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi && dockPanel.TopLevelControl is Form)
                {
                    smartPart.MdiParent = dockPanel.TopLevelControl as Form;
                    smartPart.Show();
                }
                else
                {
                    smartPart.Show(dockPanel);
                }
                #endregion
            }
            catch (Exception ex)
            {
                UtilLib.Util.Log(UtilLib.LogLevel.Error, ex);
            }
        }
    }
}
